<template>
    <table border="1">
        <tr>
            <th></th>
            <th>name</th>
            <th>price</th>
            <th>count</th>
            <th>total</th>
        </tr>
        <tr v-for="(item,index) in cartList" :key="index">
            <td><input type="checkbox" v-model="item.active"></td>
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td><span @click="plus(index)" class="btn">+</span>{{item.count}}<span @click="minus(index)" class="btn">-</span></td>
            <td>{{item.price*item.count}}</td>
        </tr>
        <tr>
            <td colspan="4">selected:{{selected}}</td>
            <td colspan="1">should pay:${{pay}}</td>
        </tr>
    </table>
</template>

<script>
    export default {
        name: "Cart",
        data(){
            return{
                cartList:[]
            }
        },
        created(){
            this.$bus.$on('addToCart',obj=>{
                //console.log(obj);
                let ret = this.cartList.find(item=>item.name===obj.name);
                if(ret){
                    ret.count+=1;
                }else{
                    this.cartList.push({...obj,count:1,active:true});
                }
                if(localStorage){
                    localStorage.setItem('cart',JSON.stringify(this.cartList));
                }
            });
            if(localStorage){
                let cart = localStorage.getItem('cart');
                if(cart){
                    this.cartList = JSON.parse(cart);
                }
            }
        },
        computed:{
            selected(){
                let s=0;
                this.cartList.forEach(item=>{
                    if(item.active){
                        s++;
                    }
                });
                return s;
            },
            pay(){
                let s=0;
                this.cartList.forEach(item=>{
                    if(item.active){
                        s+=(item.price*item.count);
                    }
                });
                return s;
            }
        },
        methods:{
            removeFromCart(index){
                if(window.confirm("really remove lesson:"+this.cartList[index].name+'?')){
                    this.cartList.splice(index,1);
                }
            },
            minus(index){
                let count = this.cartList[index].count;
                if(count===1){
                    this.removeFromCart(index);
                }else{
                    this.cartList[index].count-=1;
                }
            },
            plus(index){
                this.cartList[index].count+=1;
            },
        }
    }
</script>

<style scoped>
    .btn{
        padding: 5px;cursor:pointer;
    }
</style>